
#include <Tokens.h>

Tokens::Tokens() : head(0), num(0)
{
}

Tokens::Tokens(char* input) : head(0), num(0)
{
	read(input);
}

Tokens::Tokens(char* input, char* sep) : head(0), num(0)
{
	read(input, sep);
}

Node* Tokens::allocNode(Element elem)
{
	Node* temp;
	temp = new Node;
	temp->element = elem;
	temp->next = 0;
	return temp;
}

int Tokens::isSep(char* sep, char c)
{
	int len = strlen(sep) + 1;
	for ( int k = 0; k < len; k++ )
		if ( sep[k] == c ) return 1;
	return 0;
}

void Tokens::read(char* input, char* sep)
{
	char buf[256];
	int i, j, k;

	for ( i = 0, j = 0; input[i]; i++ ) {
		if ( isSep(sep, input[i]) ) {
			buf[j] = 0;
			if ( j )
				add(buf);
			j = 0;
		} else {
			buf[j] = input[i];
			j++;
		}
	}
	if ( j ) {
		buf[j] = 0;
		add(buf);
	}
}

void Tokens::read(char* input)
{
	read(input, " ,=:");
}

void Tokens::add(Element elem)
{
	Node *newNode, *trav;

	newNode = allocNode(elem);

	if ( !head )
		head = newNode;
	else {
		for ( trav = head; trav->next; trav = trav->next ) ;
		trav->next = newNode;
	}
	num++;
}

int Tokens::ifExists(Element elem)
{
	Node* trav;
	if ( head ) {
		for ( trav = head; trav; trav = trav->next )
			if ( trav->element == elem )
				return 1;
	}
	return 0;
}

int Tokens::numElements() const
{
	return num;
}

void Tokens::deleteAll()
{
	Node* trav;
	for ( trav = head; trav; trav = head ) {
		head = head->next;
		delete trav;
	}
}

Tokens::~Tokens()
{
	deleteAll();
}

ostream& operator<<(ostream& os, const Tokens& store)
{
	os << store.numElements() << " ";
	for ( TokensIter ti(store); ti.ok(); ti++ )
		os << ti.current()->element << " ";
	
	return os;
}


//
// Tokens Iterator
//

TokensIter::TokensIter(const Tokens& tokens)
{
	store = &tokens;
	curr = store->head;
}

TokensIter::TokensIter(const TokensIter& from)
{
	store = from.store;
	curr = from.curr;
}

TokensIter& TokensIter::operator=(const TokensIter& from)
{
	if ( this == &from ) return *this;
	store = from.store;
	curr = from.curr;
	return *this;
}

void TokensIter::reset()
{
	curr = store->head;
}

int TokensIter::ok()
{
	if ( curr ) return 1;
	return 0;
}

void TokensIter::operator++()
{
	if ( curr ) curr = curr->next;
}

Node* TokensIter::current()
{
	return curr;
}

